package cn.zqy.demo3.day01.Jdbc;


import cn.zqy.demo3.day01.Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 事务操作
 */
public class Demo10JdbcWork {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            //1.获取连接
            con = JDBCUtils.getConnection();
            //开启事务
            con.setAutoCommit(false);

            //2.定义sql
            String sql1 = "update a set  count= count - ? where id = ?";
            String sql2 = "update a set  count= count + ? where id = ?";

            //3.获取执行sql对象
            pstmt1 = con.prepareStatement(sql1);
            pstmt2 = con.prepareStatement(sql2);
            //4. 设置参数
            pstmt1.setInt(1, 500);
            pstmt1.setInt(2, 1);
            pstmt2.setInt(1, 500);
            pstmt2.setInt(2, 2);

            //5.执行sql
            pstmt1.executeUpdate();

            // 事务管理
            // 【注意】：此处如果有异常，如int a = 3/0，这种，则会导致pstmt1修改成功，pstmt2不执行
            pstmt2.executeUpdate();
            //提交事务
            con.commit();

        } catch (Exception e) {
            if (con != null ) {
                try {
                    con.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(con, pstmt1);
            JDBCUtils.close(con, pstmt2);
        }
        
    }
}
